import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartList: []//购物车列表
  },
  mutations: {
    // 购物车某商品数量+1
    addCount(state,payload) {
      payload.count++
    },
    // 添加新商品至购物车
    addToCart(state,payload) {
      payload.checked = true;
      state.cartList.push(payload)
    }
  },
  actions: {
    // 商品加入购物车或数量+1，使用promise将商品处理信息返回
    addCart(context,payload) {
      return new Promise((resolve, reject) => {
        let oldProduct = null;
        // payload新添加商品
        for(let item of context.state.cartList){
          if(item.id === payload.id){
            oldProduct = item
          }
        }
  
        // 判断oldProduct
        if(oldProduct) {
          context.commit('addCount',oldProduct)
          resolve('当前商品数量+1')
        }
        else {
          payload.count = 1
          context.commit('addToCart',payload)
          resolve('添加了新的商品')
        }
      })
    }
  },
  getters: {
    cartLength(state) {
      return state.cartList.length
    },
    cartList(state) {
      return state.cartList
    }
  },
  modules: {
  }
})
